package com.machine.filling.db.dao;

import android.provider.Settings;
import android.util.Log;

import com.machine.filling.MyApp;
import com.machine.filling.db.greendao.ExceptionOrderModleDao;
import com.machine.filling.db.modle.CardTempModle;
import com.machine.filling.db.modle.ClientInfoModle;
import com.machine.filling.db.modle.ExceptionOrderModle;
import com.machine.filling.db.modle.GunInfoModle;
import com.machine.filling.net.serialPort.receive.Receive_EndFueling;
import com.machine.filling.net.serialPort.receive.Receive_MachineState;
import com.machine.filling.util.Common;
import com.machine.filling.util.HexUtils;
import com.machine.filling.util.StringUtil;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

/**
 * Created by Administrator on 2018/3/29 0029.
 */

public class ExceptionOrderDao {
    private static ExceptionOrderDao instance;
    //    private static TempOrderModleDao tempOrderModleDao;
//    private static TempOrderModle tempOrderModle;
    private static ExceptionOrderModleDao dao;
    private static ExceptionOrderModle modle;
    private final String deviceNum;

    private ExceptionOrderDao() {
        deviceNum = Settings.System.getString(MyApp.getInstance().getContentResolver(), Settings.Secure.ANDROID_ID);

    }



    public static ExceptionOrderDao getInstance() {
        if (instance == null) {
            instance = new ExceptionOrderDao();
            dao = MyApp.getInstance().getDaoSession().getExceptionOrderModleDao();
            modle = new ExceptionOrderModle();

        }
        return instance;
    }

    public void testAddModle(ExceptionOrderModle exceptionOrderModle){
        dao.insert(exceptionOrderModle);
    }
//    public void createModle(String portNum, WsResCardInfoBean cardInfoBean) {
//        GunInfoModle gunInfoModle = GunInfoDao.getInstance().queryBytPortNum(portNum);
//        exceptionOrderModle.setCustomName(cardInfoBean.getName());
//        exceptionOrderModle.setOilCardType(cardInfoBean.getType());
//        exceptionOrderModle.setOilCardNum(cardInfoBean.getCardNum());
//        exceptionOrderModle.setOilTypeName(gunInfoModle.getTypeName());
//        exceptionOrderModle.setOilTypeUnitPrice(gunInfoModle.getPrice() + "");
//    }

//    public void setGunInfo(String portNum) {
//        GunInfoModle gunInfoModle = GunInfoDao.getInstance().queryBytPortNum(portNum);
//        tempOrderModle.setPortNum(gunInfoModle.getPortNum());
////        tempOrderModle.set
//    }

    public ExceptionOrderModle queryByPortNum(String portNum) {
        List<ExceptionOrderModle> tempOrder = dao.queryBuilder().where(ExceptionOrderModleDao.Properties.PortNum.eq(portNum)).list();
        if (tempOrder != null && tempOrder.size() != 0) {
            return tempOrder.get(tempOrder.size() - 1);
        } else {
            return null;
        }
    }

    public ExceptionOrderModle queryByOrderNum(String orderNum) {
        List<ExceptionOrderModle> tempOrder = dao.queryBuilder().where(ExceptionOrderModleDao.Properties.OrderNum.eq(orderNum)).list();
        if (tempOrder != null && tempOrder.size() != 0) {
            return tempOrder.get(tempOrder.size() - 1);
        } else {
            return null;
        }
    }

    public void deleteAll() {
        dao.deleteAll();
    }

    public void deleteByPortNum(String portNum) {
        ExceptionOrderModle modle = queryByPortNum(portNum);
        if (modle != null) {
            dao.delete(modle);
        }
    }

    /**
     * 油卡加油创建新订单
     *
     * @param portNum   串口号
     * @param orderNum  订单号
     * @param orderType 订单类型 1预约 0 非预约
     * @return 订单编号
     */
    public String createOrder_1(String portNum, String orderNum, String orderType) {
        CardTempModle card = CardTempDao.getInstance().queryByPortNum(portNum);
        GunInfoModle gun = GunInfoDao.getInstance().queryBytPortNum(portNum);
        ClientInfoModle client = ClientInfoDao.getInstance().getModleByDeviceNum();
        modle = new ExceptionOrderModle();
/*************************以下是预约订单  所需字段***********************************************/
        //todo 流水号
        //todo 订单状态
        modle.setMachineNum(client.getMachineNum());//油机编号
        if (StringUtil.isNullOrEmpty(orderNum)) {//订单编号
            orderNum = StringUtil.createOrderNum();
            modle.setOrderNum(orderNum);
        } else {
            modle.setOrderNum(orderNum);
        }
        modle.setOilPotId(gun.getPotId());//油罐id
        modle.setOilGunNum(gun.getGunNum());//油枪编号
        //todo 最终加油金额
        modle.setToken(client.getToken());//token令牌
        modle.setOilGunId(gun.getGunId());//油枪id
        modle.setMachineId(gun.getMachineId());//油机id
        modle.setPrice(gun.getPrice());//油品单价
        // TODO: 加油数量
        modle.setOilTypeName(gun.getTypeName());//油品名称
        modle.setOilTypeId(gun.getTypeId());//油品id
        modle.setCuPrice(gun.getCuPrice());//促销单价
        modle.setOilPotNum(gun.getPotNum());//油罐编号
/********************************以下是 加油订单所需字段****************************************/

        // TODO: 实付总金额

        //油机编号 上面有了

        modle.setCreateD(System.currentTimeMillis());//加油时间

        // TODO: 优惠总金额

        //订单编号,油罐id,油枪编号,Token,油枪id,  上面已有

        modle.setSellerId(client.getStationId());//商家id

        //油机id,上面已有

        modle.setOilCardId("1".equals(orderType) ? "" :card.getCardId());//油卡id

        // TODO: 加油数量

        //油品单价,油品名称,油品id,促销单价 上面已有

        // TODO: 订单状态
/********************************以下是 界面订单所需字段****************************************/

        modle.setPortNum(portNum);//串口号
        modle.setOilCardType("1".equals(orderType) ? "--" : card.getType());//油卡类型
        modle.setOilCardNum("1".equals(orderType) ? "" : card.getCardNum());//油卡编号
        modle.setCustomName("1".equals(orderType) ? "--" : card.getName());//用户姓名

        //todo 应收金额(无)

        modle.setPayState("1".equals(orderType) ? Common.ORDER_PAYED : Common.ORDER_UNPAY);//todo 支付状态(无)

        modle.setPayMode("1".equals(orderType) ? Common.PAY_MODE_ORDER : "");//支付方式,预约:预约支付;  其他的:再支付后进行刷新数据

        modle.setOrderType(orderType);//1预约 0未预约
        modle.setUploadState(Common.ORDER_UPLOADSTATE_NO);//0 未上传 1已上传

        //todo 异常原因(无)

        //todo 是否异常(无)

        dao.insert(modle);
        return orderNum;
    }

    /**
     * 油卡加油过程中 更新加油订单数据
     *
     * @param portNum
     * @param cmd_state
     */
    public void updateFuelingData_2(String portNum, Receive_MachineState cmd_state) {
        List<ExceptionOrderModle> list = dao.queryBuilder().where(ExceptionOrderModleDao.Properties.PortNum.eq(portNum)).list();
        if (list == null || list.size() == 0) {
            return;
        }
        ExceptionOrderModle orderModle = list.get(list.size() - 1);

        orderModle.setMlAmount(cmd_state.getRealQuantity() + "");//加油数量

        orderModle.setFuelMoney(cmd_state.getRealAmount() + "");//加油金额
        Log.d(TAG, "加油过程中: 加油体积" + cmd_state.getRealQuantity() + "加油金额:" + cmd_state.getRealAmount());
        dao.update(orderModle);
    }

    private static final String TAG = "ExcTempOrderDao";

    /**
     * 油卡加油结束时  更新加油的数据
     */
    public void updateFueledData_3(String portNum, Receive_EndFueling cmd_end) {
        List<ExceptionOrderModle> list = dao.queryBuilder().where(ExceptionOrderModleDao.Properties.PortNum.eq(portNum)).list();
        if (list == null || list.size() == 0) {
            return;
        }
        ExceptionOrderModle modle = list.get(list.size() - 1);

        //实付金额realMoney_9
        modle.setAmount(cmd_end.getRealMoney() + "");

        //应收金额
        int fuelMoney = HexUtils.hex2Int(cmd_end.getReceivedMoney_4());
        String fuelMoneyD = HexUtils.formatDouble(fuelMoney * 0.01, 2);
        modle.setFuelMoney(fuelMoneyD + "");

        //只有预约里面才有的
        if ("1".equals(modle.getOrderType())) {
            modle.setUsePrice(fuelMoneyD + "");
        }else {
            modle.setUsePrice( "");
        }

        //优惠金额 = 应收金额 - 实付金额
        double discountMoney = Double.parseDouble(fuelMoneyD) - cmd_end.getRealMoney();
        modle.setDiscountPrice(HexUtils.formatDouble(discountMoney, 2));

        //加油体积
        String volume = HexUtils.formatDouble(cmd_end.getSheng(),2);
        modle.setMlAmount(volume);

        //凭证号  流水号
        modle.setMachineFlowNum(cmd_end.getErialNum_2());

        Log.d(TAG, "updateFueledData_3() returned: 加油结束: \n体积:" + HexUtils.formatDouble(cmd_end.getSheng(),2)
                + "\n应收金额:" + fuelMoneyD + "\n实付金额:" + cmd_end.getRealMoney() + "\n优惠:" + HexUtils.formatDouble(discountMoney, 2));
        dao.update(modle);
    }

    /**
     * 更新订单状态 是否已经联网上传订单
     *
     * @param portNum
     * @param isSuccess
     * @param errorReason
     */
    public void updateOrderUploadState(String portNum, boolean isSuccess, String errorReason) {
        List<ExceptionOrderModle> list = dao.queryBuilder().where(ExceptionOrderModleDao.Properties.PortNum.eq(portNum)).list();
        if (list == null || list.size() == 0) {
            return;
        }
        ExceptionOrderModle modle = list.get(list.size() - 1);

        if (isSuccess) {
            modle.setUploadState(Common.ORDER_UPLOADSTATE_YES);//订单上传状态
            modle.setPayMode(Common.PAY_MODE_ORDER);//支付方式
            modle.setIsError(false);//是否异常
        } else {
            modle.setUploadState(Common.ORDER_UPLOADSTATE_NO);//订单上传状态
            modle.setIsError(true);//是否异常 异常
            modle.setReason(errorReason);//异常信息
        }

        dao.update(modle);
    }

    /**
     * 根据订单编号  修改 订单上传状态
     * @param orderNum
     * @param isSuccess
     * @param errorReason
     */
    public void updateOrderUploadStateByOrderNum(String orderNum, boolean isSuccess, String errorReason) {
        List<ExceptionOrderModle> list = dao.queryBuilder().where(ExceptionOrderModleDao.Properties.OrderNum.eq(orderNum)).list();
        if (list == null || list.size() == 0) {
            return;
        }
        ExceptionOrderModle modle = list.get(list.size() - 1);

        if (isSuccess) {
            modle.setUploadState(Common.ORDER_UPLOADSTATE_YES);//订单上传状态
            modle.setPayMode(Common.PAY_MODE_ORDER);//订单支付方式
            modle.setIsError(false);//是否异常
        } else {
            modle.setUploadState(Common.ORDER_UPLOADSTATE_NO);//订单上传状态
            modle.setIsError(true);//是否异常 异常
            modle.setReason(errorReason);//异常信息
        }

        dao.update(modle);
    }

    /**
     * 查询制定日期内数据
     *
     * @param date1     时间戳1
     * @param date2     时间戳2
     * @param isOrdered 0预约 1未预约 2全部
     * @return
     */
    public List<ExceptionOrderModle> queryAllDesc(long date1, long date2, String isOrdered) {
        QueryBuilder queryBuilder = dao.queryBuilder();
        //时间区间筛选
        queryBuilder = queryBuilder.where(ExceptionOrderModleDao.Properties.CreateD.between(date1, date2));
        //订单状态筛选
        if (!"2".equals(isOrdered)) {
            queryBuilder = queryBuilder.where(ExceptionOrderModleDao.Properties.OrderType.eq(isOrdered));
        }

        return queryBuilder.orderDesc(ExceptionOrderModleDao.Properties.CreateD).list();
    }

    /**
     * 带分页的查询
     * @param date1
     * @param date2
     * @param isOrdered
     * @param pageSize 第几页 从1 开始
     * @param contentCount 一页有多少数据
     * @return
     */
    public List<ExceptionOrderModle> queryAllDescWithPage(long date1, long date2,
                                                          String isOrdered,int pageSize,int contentCount) {
        QueryBuilder queryBuilder = dao.queryBuilder();
        //时间区间筛选
        queryBuilder = queryBuilder.where(ExceptionOrderModleDao.Properties.CreateD.between(date1, date2));
        //订单状态筛选
        if (!"2".equals(isOrdered)) {
            queryBuilder = queryBuilder.where(ExceptionOrderModleDao.Properties.OrderType.eq(isOrdered));
        }

        return queryBuilder.orderDesc(ExceptionOrderModleDao.Properties.CreateD)
                .offset((pageSize-1) * contentCount)//从第x*20个开始查询
                .limit(contentCount)//每页显示20个
                .list();
    }

    /**
     * 更新支付方式
     *
     * @param portNum
     * @param payMode
     */
    public void upadteOrderPayMode(String portNum, String payMode) {
        List<ExceptionOrderModle> list = dao.queryBuilder().where(ExceptionOrderModleDao.Properties.PortNum.eq(portNum)).list();
        if (list == null || list.size() == 0) {
            return;
        }
        ExceptionOrderModle modle = list.get(list.size() - 1);
        modle.setPayMode(payMode);//支付方式
        dao.update(modle);
    }

    /**
     * 根据订单编号 修改支付方式
     * @param orderNum
     * @param payMode
     */
    public void upadteOrderPayModeByOrderNum(String orderNum, String payMode) {
        List<ExceptionOrderModle> list = dao.queryBuilder().where(ExceptionOrderModleDao.Properties.OrderNum.eq(orderNum)).list();
        if (list == null || list.size() == 0) {
            return;
        }
        ExceptionOrderModle modle = list.get(list.size() - 1);
        modle.setPayMode(payMode);//支付方式
        dao.update(modle);
    }

//    /**
//     * 更新预约订单的 订单上传的状态
//     *
//     * @param portNum 串口号
//     * @param uploadSuccess  (uploadState 是否上传  0 未上传 1已上传)
//     */
//    public void setOrderUploadState(String portNum, boolean uploadSuccess) {
//        List<ExceptionOrderModle> list = dao.queryBuilder().where(ExceptionOrderModleDao.Properties.PortNum.eq(portNum)).list();
//        if (list == null || list.size() == 0) {
//            return;
//        }
//        ExceptionOrderModle tempOrder = list.get(list.size() - 1);
//        if (uploadSuccess) {
//            tempOrder.setUploadState("1");
//        } else {
//            tempOrder.setUploadState("0");
//        }
//        tempOrder.setPayMode(Common.PAY_MODE_ORDER);
//        dao.update(tempOrder);
//    }

    /**
     * 更新订单的支付状态
     *
     * @param portNum
     * @param orderPayState 1未支付  2已支付未写卡  3已支付
     * @param failedMsg     支付失败的原因
     */
    public void updateOrderPayState(String portNum, String orderPayState, String failedMsg) {
        List<ExceptionOrderModle> list = dao.queryBuilder().where(ExceptionOrderModleDao.Properties.PortNum.eq(portNum)).list();
        if (list == null || list.size() == 0) {
            return;
        }
        ExceptionOrderModle modle = list.get(list.size() - 1);
        modle.setPayState(orderPayState);//支付状态
        modle.setReason(failedMsg);
        dao.update(modle);
    }

    /**
     *  根据订单编号 修改支付状态
     * @param orderNum
     * @param orderPayState
     * @param failedMsg
     */
    public void updateOrderPayStateByOrderNum(String orderNum, String orderPayState, String failedMsg) {
        List<ExceptionOrderModle> list = dao.queryBuilder().where(ExceptionOrderModleDao.Properties.OrderNum.eq(orderNum)).list();
        if (list == null || list.size() == 0) {
            return;
        }
        ExceptionOrderModle modle = list.get(list.size() - 1);
        modle.setPayState(orderPayState);//支付状态
        modle.setReason(failedMsg);
        dao.update(modle);
    }

    /**
     * 更新订单号
     *
     * @param portNum
     * @param orderNum
     */
    public void upadteOrderNum(String portNum, String orderNum) {
        List<ExceptionOrderModle> list = dao.queryBuilder().where(ExceptionOrderModleDao.Properties.PortNum.eq(portNum)).list();
        if (list == null || list.size() == 0) {
            return;
        }
        ExceptionOrderModle modle = list.get(list.size() - 1);
        modle.setOrderNum(orderNum);//订单号
        dao.update(modle);
    }

}
